package com.cly.service.impl;

import cn.hutool.core.util.EnumUtil;
import com.cly.base.contants.CacheKeysConstants;
import com.cly.entity.Problem;
import com.cly.enums.ProblemTypeEnum;
import com.cly.mapper.ProblemMapper;
import com.cly.result.JsonRequest;
import com.cly.service.IExamStatisticsService;
import com.cly.statistics.PieStatistics;
import com.cly.statistics.SumStatistics;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 考试统计服务实现
 *
 * @author by 春风能解释
 * <p>
 * 2024/10/15
 */
@Service
@RequiredArgsConstructor
public class ExamStatisticsServiceImpl implements IExamStatisticsService {

    /**
     * 题目服务
     */
    private final ProblemMapper problemMapper;

    /**
     * 考试总数
     *
     * @return 考试总数
     */
    @Override
    @Cacheable(value = CacheKeysConstants.ExamKeys.EXAM_COUNT)
    public JsonRequest<List<SumStatistics<Long>>> sumStatisticsExam() {
        return JsonRequest.success(problemMapper.sumStatisticsProblem());
    }

    /**
     * 试题类型统计
     *
     * @return 试题类型统计
     */
    @Override
    @Cacheable(value = CacheKeysConstants.ExamKeys.EXAM_TYPE)
    public JsonRequest<List<PieStatistics<Long>>> sumStatisticsExamType() {
        List<Problem> problems = problemMapper.selectList(null);
        Map<String, PieStatistics<Long>> map = new HashMap<>();
        for (Problem problem : problems) {
            ProblemTypeEnum typeEnum = EnumUtil.getBy(ProblemTypeEnum.class, problemTypeEnum -> problemTypeEnum.getValue().equals(problem.getType()));
            PieStatistics<Long> statistics = map.get(typeEnum.getName());
            if (statistics == null) {
                statistics = new PieStatistics<>();
                statistics.setName(typeEnum.getName());
                statistics.setValue(1L);
                map.put(typeEnum.getName(), statistics);
            } else {
                statistics.setValue(statistics.getValue() + 1L);
            }
        }
        return JsonRequest.success(new ArrayList<>(map.values()));
    }
}
